﻿;;
;; Trackpoint.ahk
;; Author: Chiyuan Zhang <pluskid@gmail.com>
;; Version: 1.0 (Sep. 03, 2009)
;;
;; Thinkpad trackpoint driver on Windows doesn't allow
;; to use both middle-click and scrolling simultaneously.
;; If you enable the scrolling, you'll not be able to
;; click the middle button (e.g. to open a link in the
;; background in Firefox). 
;;
;; However, on Linux, one can get a good behavior where
;; both middle-click and scrolling behaves well (see
;; www.thinkwiki.org/wiki/How_to_configure_the_TrackPoint).
;;
;; This script trys to make it behave similarly. When you
;; press the middle button and release in a short time, it
;; will be a regular middle-click. However, if you hold it
;; and move the cursor, it will do scrolling.
;;
 
;; Configuration
 
;#NoTrayIcon
 
; Milliseconds threshold, hold the middle button for some time
; exceeding this will start to detect scrolling.
tp_StartScrollTThreshold = 50
; Pixels threshold, for both X and Y. Only when the mouse movement
; exceed this threshold will we start scrolling. 
tp_StartScrollXThreshold = 7
tp_StartScrollYThreshold = 4
; Milliseconds interval to check further scrolling. Set this to a
; smaller value will make scrolling more fast, and vice versa.
tp_ScrollCheckInterval = 50
 
;; This key/Button activates scrolling
tp_TriggerKey = MButton
 
;; End of configuration
 
#Persistent
CoordMode, Mouse, Screen
Hotkey, %tp_TriggerKey%, tp_TriggerKeyDown
HotKey, %tp_TriggerKey% Up, tp_TriggerKeyUp
return
 
tp_TriggerKeyDown:
tp_Scroll = n
MouseGetPos, tp_OrigX, tp_OrigY
SetTimer, tp_CheckForScrollEventAndExecute, %tp_StartScrollTThreshold%
return
 
tp_TriggerKeyUp:
SetTimer, tp_CheckForScrollEventAndExecute, Off
;; Send a middle-click if we did not scroll
if tp_Scroll = n
    MouseClick, Middle
return
 
tp_CheckForScrollEventAndExecute:
tp_Scroll = y
SetTimer, tp_CheckForScrollEventAndExecute, %tp_ScrollCheckInterval%
 
MouseGetPos, tp_NewX, tp_NewY
tp_DistanceX := tp_NewX - tp_OrigX
tp_DistanceY := tp_NewY - tp_OrigY
 
if tp_DistanceY > %tp_StartScrollYThreshold%
    MouseClick, WheelDown
else if tp_DistanceY < -%tp_StartScrollYThreshold%
    MouseClick, WheelUp
 
; 0x114 is WM_HSCROLL
if tp_DistanceX > %tp_StartScrollXThreshold%
{
    ControlGetFocus, FocusedControl, A
    SendMessage, 0x114, 1, 0, %FocusedControl%, A
}
else if tp_DistanceX < -%tp_StartScrollXThreshold%
{
    ControlGetFocus, FocusedControl, A
    SendMessage, 0x114, 0, 0, %FocusedControl%, A
}
 
return